package com.xinwei.controller.interceptor;

import com.xinwei.excpetion.ManagerException;
import com.xinwei.excpetion.ManagerExceptionEnmu;
import com.xinwei.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenBasedAccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String uri = request.getRequestURI();
        if (uri.contains("/login")){
            return true;
        }else{
            try {
                JWTUtils.verify(token);
            } catch (Exception e) {
                //这里重新设置返回的数据
                //1、重置response
                response.reset();
                //2、设置编码格式
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json;charset=utf-8");

                PrintWriter pw = response.getWriter();
                pw.write("{\n" +
                        "    \"status\": 10001,\n" +
                        "    \"msg\": \"error token\",\n" +
                        "    \"data\": null\n" +
                        "}");
                pw.flush();
                pw.close();
                return false;
            }
            return true;
        }
    }

}
